package algorithm.sort;

import java.util.Arrays;

import static algorithm.sort.SortUtil.swap;

/**
 * 选择排序
 *
 * @author hck
 */
public class SelectSort {
    public static void main(String[] args) {
        int[] array = {6, 8, 1, 9, 2, 5, 4, 3, 7};
        System.out.println("source array: " + Arrays.toString(array));
        sort(array);
        System.out.println("sorted array: " + Arrays.toString(array));
    }

    /**
     * 选择排序
     *
     * @param array
     */
    public static void sort(int[] array) {
        if (null == array || array.length == 0 || array.length == 1) {
            return;
        }
        int count = 0;
        //  第N个最小数
        for (int i = 0; i < array.length; i++) {
            int min = array[i];
            int minIndex = -1;
            //  从N个最小数的下一个开始查找最小的
            for (int j = i + 1; j < array.length; j++) {
                if (array[j] < min) {
                    min = array[j];
                    minIndex = j;
                    count++;
                }
            }
            if (minIndex != -1) {
                swap(array, i, minIndex);
            }
        }
        System.out.println("次数:" + count);
    }
}
